# Create your views here.
from django.shortcuts import render_to_response
from google.appengine.api import users
from django import http
from django.core.paginator import Paginator, InvalidPage
from google.appengine.ext import db
from django.conf import settings

import os
import logging

from models import FlickrOption, Photo
from forms import FlickrOptionForm, PhotoForm

def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}
  if user:
    params['user'] = user
    params['sign_out'] = users.CreateLogoutURL('/')
    params['is_admin'] = (users.IsCurrentUserAdmin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.CreateLoginURL(request.path)
  if not template.endswith('.html'):
    template += '.html'
  return render_to_response(template, params)


def index(request, page_num = 1):
  """Request / -- show the last photo."""
  user = users.GetCurrentUser()  
  photos = Photo.all().order('-pub_date').fetch(limit=5)
  paginate_by = 1 #always show only one photo
  info_list = Paginator(photos,  paginate_by)  
  try:
    page_info = info_list.page(page_num)
  except InvalidPage:
    page_num = 1
    page_info = info_list.page(page_num)

  has_previous = page_info.has_previous()
  has_next = page_info.has_next()
  
  title=desc=''
  try:
    title = page_info.object_list[0].title
    desc = page_info.object_list[0].body
  except:
    pass
  
  #eval here converts string into dict
  thumb_url = thumb_source = thumb_width = thumb_height = ''
  try:    
    thumb_info    = eval(page_info.object_list[0].thumb_info)
    thumb_url     = thumb_info['url']
    thumb_source  = thumb_info['source']
    thumb_width   = thumb_info['width']
    thumb_height  = thumb_info['height']
  except:
    pass
  
  photo_url = photo_source = photo_width = photo_height = ''
  try:    
    photo_info    = eval(page_info.object_list[0].photo_info)
    photo_url     = photo_info['url']
    photo_source  = photo_info['source']
    photo_width   = photo_info['width']
    photo_height  = photo_info['height']
  except:
    pass
  
  exposure_prg = iso = date_taken = aperture = model = exposure = ''
  try:    
    exif_info     = eval(page_info.object_list[0].exif_info)
    exposure_prg  = exif_info['exposure_prg']
    iso           = exif_info['iso']
    date_taken    = exif_info['date_taken']
    aperture      = exif_info['aperture']
    model         = exif_info['model']
    exposure      = exif_info['exposure']
  except:
    pass
  
  info_dict = {
    'title'         : title,
    'desc'          : desc,
    'thumb_url'     : thumb_url,
    'thumb_source'  : thumb_source,
    'thumb_width'   : thumb_width,
    'thumb_height'  : thumb_height,
    'photo_url'     : photo_url ,
    'photo_source'  : photo_source,
    'photo_width'   : photo_width,
    'photo_height'  : photo_height,
    'exposure_prg'  : exposure_prg,
    'iso'           : iso,
    'date_taken'    : date_taken,
    'aperture'      : aperture,
    'model'         : model,
    'exposure'      : exposure,
    'has_previous'  : page_info.has_previous(),
    'previous_page' : page_info.previous_page_number(),
    'has_next'      : page_info.has_next(),
    'next_page'     : page_info.next_page_number(),
    'site_name' : settings.SITE_NAME,
    }
    
  template_name = 'index'
  return respond(request, user, template_name, info_dict)

def browse(request):
  """Request / -- show all photos."""
  user = users.GetCurrentUser()
  photos = db.GqlQuery('SELECT * FROM Photo ORDER BY pub_date DESC')  
  return respond(request, user, 'list', {'photos': photos})


def editPhoto(request, photo_id):
  """Create or edit a photo.  GET shows a blank form, POST processes it."""
  admin_user = users.IsCurrentUserAdmin()
  if admin_user is None:
    return http.HttpResponseForbidden('You must be signed in as an admin to add/edit a photo')

  photo = None
  if photo_id:
    photo = Photo.get(db.Key.from_path(Photo.kind(), int(photo_id)))
    if photo is None:
      return http.HttpResponseNotFound('No photo exists with that key (%r)' %
                                       photo_id)
    
  form = PhotoForm(data=request.POST or None, instance=photo)
  
  if not request.POST:
    return respond(request, admin_user, 'photo', {'form': form, 'photo': photo})

  errors = form.errors
  if not errors:
    try:
      photo = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return respond(request, user, 'photo', {'form': form, 'photo': photo})

  #finally save
  photo.put()
  return http.HttpResponseRedirect('/')

def newPhoto(request):
  """add a new photo.  GET shows a blank form, POST processes it."""
  return editPhoto(request, None)

def flickrOption(request):
  """Create or edit Flickr Options. GET shows a blank form, POST processes it."""
  admin_user = users.IsCurrentUserAdmin()
  if admin_user is None:
    return http.HttpResponseForbidden('You must be signed in as an admin to add/edit Flickr Options')

  FOption = None
  FOption = FlickrOption.gql("LIMIT 1")
  try:
    instance = FOption[0]
  except:
    instance = None

  form = FlickrOptionForm(data=request.POST or None, instance=instance)

  if not request.POST:
    return respond(request, admin_user, 'flickroption', {'form': form, 'flickrOption': FOption})

  errors = form.errors
  if not errors:
    try:
      FOption = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:    
    return respond(request, admin_user, 'flickroption', {'form': form, 'flickrOption': FOption})

  #finally save
  FOption.put()
  return http.HttpResponseRedirect('/')

def about(request):
  user = users.GetCurrentUser()
  template = 'about'
  return respond(request, user, template)